package com.scut.chenlujie.library.clink.sample.server;

import com.scut.chenlujie.library.clink.core.IoContext;
import com.scut.chenlujie.library.clink.impl.IoSelectorProvider;
import com.scut.chenlujie.library.clink.impl.SchedulerImpl;
import com.scut.chenlujie.library.clink.sample.foo.FooGui;
import com.scut.chenlujie.library.clink.sample.foo.constants.TCPConstants;
import com.scut.chenlujie.library.clink.sample.foo.foo;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Server {
    public static void main(String[] args) throws IOException {
        File cachePath = foo.getCacheDir("server");
        IoContext.setup()
                .ioProvider(new IoSelectorProvider())
                .scheduler(new SchedulerImpl(1))
                .start();
        TCPServer tcpServer = new TCPServer(TCPConstants.PORT_SERVER,cachePath);
        boolean isSucceed = tcpServer.start();
        if (!isSucceed) {
            System.out.println("Start TCP server failed!");
            return;
        }

        UDPProvider.start(TCPConstants.PORT_SERVER);
        // 界面显示
        FooGui gui = new FooGui("Clink-Server", new FooGui.Callback() {
            @Override
            public Object[] takeText() {
                return tcpServer.getStatusString();
            }
        });
        gui.doShow();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String str;
        do {
            str = bufferedReader.readLine();
            if(str == null || foo.COMMAND_EXIT .equalsIgnoreCase(str)){
               break;
            }
            if(str.length() == 0 ){
                continue;
            }
            tcpServer.broadcast(str);
        } while (true);

        //不监听udp端口了
        UDPProvider.stop();
        tcpServer.stop();

        IoContext.close();
        gui.doDismiss();
    }
}
